<template>
  <div class="video-container">
    <a-spin :spinning="isLoadingVideo && !fullScreenLoading">
      <div class="video glplayer-container" v-show="isPlay" :id="elId"></div>
      <div v-show="!isPlay" class="no-video">
        <!-- <slot></slot> -->
        <no-video />
      </div>
      <VideoControl
        ref="videoControlRef"
        @recordOperate="recordOperate"
        @screenShot="screenShot"
        @fullscreen="fullscreen"
        @closeVideo="closeVideo"
        :additional="additional"
        :url="url"
        v-show="isPlay"
        @handleClick="handleClick"
        :noShowRecord="noShowRecord"
      >
      </VideoControl>
    </a-spin>

    <div
      v-if="fullScreenLoading && isLoadingVideo"
      class="video-player-full-screen flex justify-center items-center"
    >
      <a-spin :spinning="true" tip="视频加载中"><span></span></a-spin>
    </div>
  </div>
</template>

<script lang="ts">
import { ref, onMounted, onBeforeUnmount, defineComponent } from 'vue'
import VideoControl from './videoControl.vue'
// @ts-ignore
import { ysFixWebmDuration } from './utils/fix-webm-duration-2.js'
// @ts-ignore
// import { saveAs } from 'file-saver'
import { download } from '@/utils/download'
import { addStreamProxy } from './serve.api'

export default defineComponent({
  name: 'lnVideoPlayer',
  components: {
    VideoControl
  },
  props: {
    url: {
      type: String,
      default: ''
    },
    // host: {
    //   type: String,
    //   default: "",
    // },
    model: {
      type: String,
      default: 'hls'
    },
    additional: {
      type: Array,
      default: () => []
    },
    closeVideoClick: {
      type: Boolean,
      default: true
    },
    noShowRecord: {
      type: Boolean,
      default: false
    },
    fullScreenLoading: {
      type: Boolean,
      default: false
    }
  },
  setup(props, { emit }) {
    const isPlay = ref(false)
    const isLoadingVideo = ref(false)
    const elId: string = 'elId' + Date.now()
    const videoId: string = elId + '-flv-hevc'

    let player: any = null
    let localMediaRecorder: any = null
    let startRecordTime: number = 0
    const chunks: Array<any> = []
    const ifRecord = ref(false) // 是否正在录屏
    const videoControlRef = ref()
    onMounted(() => {
      // console.log(props);
    })
    onBeforeUnmount(() => {
      closePlayer()
    })
    const createPlayer = async () => {
      console.log(props.url, '-----------props.url-----------')
      if (!props.url) return
      try {
        isLoadingVideo.value = true
        closePlayer()
        const url = props.url
        const data = await addStreamProxy({
          url,
          enableHls: false
        })
        const wsUrl = `ws://${data.host}/${data.app}/${data.stream}.live.flv`
        // const wsUrl = 'ws://192.168.6.99:8888/live/9fa1a17064d578cc5eaf2eb42a3ac045.live.flv'

        console.log(wsUrl)
        isPlay.value = true
        const H265JS_DEFAULT_PLAYER_CONFIG = {
          player: elId,
          ignoreAudio: 1,
          // token:
          //   'base64:QXV0aG9yOmNoYW5neWFubG9uZ3xudW1iZXJ3b2xmLEdpdGh1YjpodHRwczovL2dpdGh1Yi5jb20vbnVtYmVyd29sZixFbWFpbDpwb3JzY2hlZ3QyM0Bmb3htYWlsLmNvbSxRUTo1MzEzNjU4NzIsSG9tZVBhZ2U6aHR0cDovL3h2aWRlby52aWRlbyxEaXNjb3JkOm51bWJlcndvbGYjODY5NCx3ZWNoYXI6bnVtYmVyd29sZjExLEJlaWppbmcsV29ya0luOkJhaWR1',
          extInfo: {
            moovStartFlag: true
          }
        }
        const resolveConfig = (conf?: Record<string, any>) =>
          Object.assign(H265JS_DEFAULT_PLAYER_CONFIG, conf)
        // @ts-ignore
        player = window.new265webjs(wsUrl, resolveConfig())
        // 媒体文件加载完成事件，媒体文件当前加载成功，可以进行播放
        player.onLoadFinish = () => {
          if (player === null) return
          isLoadingVideo.value = false
          player.onPlayState = (state: boolean) => {
            if (state) {
              console.log('视频播放')
              emit('isPauseVide', false)
            } else {
              console.log('视频暂停')
              emit('isPauseVide', true)
              setTimeout(() => {
                // 处理切换窗口后视频暂停问题
                if (document.visibilityState === 'hidden') player?.play()
              })
            }
          }
        }
        // 播放器封面图加载完成
        player.onReadyShowDone = () => {
          // 解决多次点击生成多个video dom问题
          const playerContainer = document.getElementById(elId)
          const childNodes = playerContainer?.childNodes
          childNodes?.forEach((cNode, index) => {
            if (index !== childNodes.length - 1) {
              playerContainer?.removeChild(cNode)
            }
          })
          const videoElement: any = document.getElementById(videoId)
          if (videoElement && videoElement.tagName === 'VIDEO') {
            videoElement.muted = true
          }
          player?.play()
        }
        player.onPlayTime = (pts: number) => {
          emit('timeupdate', pts)
        }
        // 加载播放器
        player.do()
      } catch (err) {
        closeVideo()
        isLoadingVideo.value = false
        console.error(err)
        emit('addStreamFail') // 获取视频流失败,如播放异常，请检查相机是否在线
      }
    }
    // 关闭视频事件
    const closePlayer = () => {
      console.log('关闭视频')
      isPlay.value = false
      stopRecord()
      if (player) {
        player.release()
      }
      player = null
    }
    // 截屏
    const screenShot = () => {
      if (player) {
        const videoElement = document.getElementById(
          videoId
        ) as HTMLVideoElement
        if (videoElement && videoElement.tagName === 'VIDEO') {
          const canvas = document.createElement('canvas')
          const ctx = canvas.getContext('2d')
          canvas.width = videoElement.videoWidth
          canvas.height = videoElement.videoHeight
          ctx!.drawImage(videoElement, 0, 0)
          // download picture
          const a = document.createElement('a')
          a.href = canvas.toDataURL('image/png')
          a.download = `截图-${Date.now()}`
          a.click()
        }
      }
    }
    // 全屏
    const fullscreen = () => {
      player?.fullScreen()
      // if (player) {
      //   const videoElement = player.video
      //   if (videoElement.requestFullscreen) videoElement.requestFullscreen()
      //   else if (videoElement.mozRequestFullScreen)
      //     videoElement.mozRequestFullScreen()
      //   else if (videoElement.webkitRequestFullScreen)
      //     videoElement.webkitRequestFullScreen()
      // }
    }
    // 关闭视频
    const closeVideo = () => {
      emit('closeVideo')
      closePlayer()
    }

    // 录屏
    const recordOperate = async (flag: { value: any }) => {
      ifRecord.value = flag.value
      if (flag.value) {
        record()
      } else {
        stopRecord()
      }
    }

    const record = () => {
      emit('ifRecord', true)
      if (localMediaRecorder) {
        localMediaRecorder.start()
      } else {
        const videoElement = document.getElementById(videoId) as any
        localMediaRecorder = new MediaRecorder(videoElement.captureStream(25), {
          audioBitsPerSecond: 128000, // 音频码率
          videoBitsPerSecond: 2500000, // 视频码率
          mimeType: 'video/webm;codecs=vp8,opus'
        })
        localMediaRecorder.blobs = []
        // 录屏结果
        localMediaRecorder.ondataavailable = (e: any) => {
          localMediaRecorder.blobs.push(e.data)
          chunks.push(e.data)
        }

        // 录屏开始
        localMediaRecorder.onstart = (e: any) => {
          startRecordTime = new Date().getTime()
        }
        // 录屏结束
        localMediaRecorder.onstop = (e: any) => {
          console.log(e)
          const duration = new Date().getTime() - startRecordTime
          const tmpBlob = new Blob(chunks, {
            type: 'video/webm;codecs=vp8,opus'
          })
          ysFixWebmDuration(tmpBlob, duration, (fixedBlob: BlobPart) => {
            const file = new File([fixedBlob], `${Date.now()}.webm`, {
              type: 'video/webm'
            })
            download('未命名', file)
            chunks.length = 0
            localMediaRecorder.blobs = []
            localMediaRecorder = null
            ifRecord.value = false
            videoControlRef.value.recordType = false
          })
        }
        localMediaRecorder.start()
      }
    }

    const stopRecord = () => {
      emit('ifRecord', false)
      try {
        localMediaRecorder?.stop()
      } catch (e) {
        console.log(e)
      }
    }

    const handleClick = (event: string) => {
      emit(event, player)
    }

    // 暂停视频
    const pauseVideo = (flag: Boolean) => {
      // flag: true 暂停; false 播放
      if (player) {
        if (flag) {
          // player.video.pause()
          console.log('暂停')
          player.pause()
        } else {
          // player.video.play()
          player.play()
        }
      }
    }

    return {
      isPlay,
      isLoadingVideo,
      elId,
      ifRecord,
      createPlayer,
      closeVideo,
      screenShot,
      fullscreen,
      recordOperate,
      closePlayer,
      handleClick,
      pauseVideo,
      videoControlRef
    }
  }
})
</script>

<style lang="less">
@import './index.less';

.glplayer-container video {
  width: 100% !important;
  height: 100% !important;
  object-fit: fill;
}

.glplayer-container canvas {
  width: 100% !important;
  height: 100% !important;
  object-fit: fill;
}

.video-player-full-screen {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 999;

  .ant-spin {
    min-height: 100%;

    .ant-spin-text {
      text-shadow: none !important;
    }
  }
}
</style>
